<template>
    <u-popup :show="value" :round="10" mode="bottom" @close="$emit('input', false)" @open="open">
        <view class="popup-body">
            <!-- 标题 -->
            <view class="title">{{ record ? '编辑消费记录' : '新增消费记录' }}</view>

            <!-- 表单 -->
            <u--form ref="form" :model="recordForm" :rules="rules" labelPosition="left" labelWidth="100">
                <!-- 备注 -->
                <u-form-item label="备注">
                    <u--input v-model="recordForm.remark" placeholder="支出/收入备注" clearable border="surround"></u--input>
                </u-form-item>

                <!-- 消费类型 -->
                <u-form-item label="消费类型" prop="typeId" @click="typePickerShow = true">
                    <u--input v-model="selectedTypeName" readonly placeholder="请选择类型" border="surround"></u--input>
                    <u-picker :show="typePickerShow" :columns="[types.map(item => item.name)]"
                        @cancel="typePickerShow = false" @confirm="onTypeConfirm">
                    </u-picker>
                </u-form-item>

                <!-- 金额 -->
                <u-form-item label="金额" prop="money">
                    <u--input v-model="recordForm.money" type="digit" placeholder="请输入内容" :min="0" border="surround"
                        clearable></u--input>
                </u-form-item>

                <!-- 时间 -->
                <u-form-item label="时间" prop="createTime" @click="openDatePicker">
                    <u--input v-model="recordForm.createTime" readonly placeholder="请选择类型" border="surround"></u--input>
                    <u-datetime-picker :show="timePickerShow" @confirm="onTimeConfirm"
                        @cancel="timePickerShow = false" v-model="tempCreateTime" mode="datetime"
                        :formatter="dateFormatter"></u-datetime-picker>
                </u-form-item>

                <!-- 支出账户 -->
                <u-form-item label="账户" prop="payAccountId" @click="payAccountPickerShow = true">
                    <u--input v-model="selectedPayName" readonly placeholder="请选择账户" border="surround"></u--input>
                    <u-picker :show="payAccountPickerShow" :columns="[pays.map(item => item.name)]" @confirm="onPayConfirm">
                    </u-picker>
                </u-form-item>
            </u--form>

            <!-- 开关选项 -->
            <view class="switch-group">
                <u-switch v-model="incomeOrExpense"></u-switch>
                <text class="switch-label">{{ incomeOrExpense ? '记为收入' : '记为支出' }}</text>
            </view>

            <view class="switch-group">
                <u-switch v-model="intervalRecording"></u-switch>
                <text class="switch-label">{{ intervalRecording ? '区间消费' : '普通消费' }}</text>
            </view>

            <view v-if="intervalRecording" class="switch-group">
                <u-calendar v-model="timeSlot" mode="range"></u-calendar>
            </view>

            <view v-if="intervalRecording" class="switch-group">
                <u-switch v-model="excludeWorkingDays"></u-switch>
                <text class="switch-label">排除工作日</text>
            </view>

            <view class="switch-group">
                <u-switch v-model="addTags"></u-switch>
                <text class="switch-label">添加标签</text>
            </view>

            <!-- 底部操作按钮 -->
            <view class="footer-btns u-flex u-row-between u-m-t-20">
                <u-button @click="$emit('input', false)">取消</u-button>
                <u-button type="primary" @click="saveOrEditSubmit">{{ record ? '保存' : '添加' }}</u-button>
            </view>
        </view>
    </u-popup>
</template>

<script>
import { addRecordReq, getPayAccount, getRecordById, getRecordTypes } from "@/api/finance";
import {formatTimestamp} from "@/utils/commonUtil";

export default {
    props: {
        value: { // v-model 控制弹窗显示
            type: Boolean,
            default: false
        },
        editRecordId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            record: null,
            recordForm: {
                remark: '',
                typeId: '',
                money: 0,
                createTime: '',
                payAccountId: ''
            },
            types: [],
            pays: [],
            selectedTypeName: '',
            selectedPayName: '',
            incomeOrExpense: false,
            intervalRecording: false,
            addTags: false,
            excludeWorkingDays: false,
            typePickerShow: false,
            timePickerShow: false,
            tempCreateTime: '',
            payAccountPickerShow:false,
            timeSlot: [],
            rules: {
                typeId: [{ required: true, message: '请选择消费类型', trigger: 'blur' }],
                money: [{ required: true, message: '请输入金额', trigger: 'blur' }],
                createTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
                payAccountId: [{ required: true, message: '请选择支出账户', trigger: 'blur' }]
            }
        }
    },
    mounted() {
        this.initEditData()
        this.initPayAccount()
        this.initTypes()
    },
    methods: {
        open() {
            
        },
        initPayAccount() {
            getPayAccount()
                .then(res => {
                    this.pays = res.list
                })
                .catch(err => {
                    console.error("获取支出账户失败", err);
                });
        },
        initTypes() {
            getRecordTypes()
                .then(res => {
                    this.types = res.list
                })
                .catch(err => {
                    console.error("获取支出账户失败", err);
                });
        },
        initEditData() {
            if (!this.editRecordId) return
            getRecordById({ id: this.editRecordId }).then(res => {
                this.record = res
                this.recordForm = res
            })
        },
        onTypeConfirm(e) {
            let index = e.indexs[0]
            let type = this.types[index]
            this.recordForm.typeId = type.id
            this.selectedTypeName = type.name
            this.typePickerShow = false
        },
        onPayConfirm(e) {
            let index = e.indexs[0]
            let pay = this.pays[index]
            this.recordForm.payAccountId = pay.id
            this.selectedPayName = pay.name
            this.payAccountPickerShow = false
        },
        saveOrEditSubmit() {
            this.$refs.form.validate().then(valid => {
                if (valid) {
                    this.recordForm.incomeOrExpense = this.incomeOrExpense
                    this.recordForm.addTags = this.addTags
                    if (this.intervalRecording) {
                        this.recordForm.intervalRecording = true
                        this.recordForm.excludeWorkingDays = this.excludeWorkingDays
                        this.recordForm.timeSlot = this.timeSlot
                    }
                    addRecordReq(this.recordForm).then(() => {
                        this.$emit("successThen")
                        this.$emit("input", false)
                    })
                }
            })
        },
        dateFormatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            if (type === 'day') {
                return `${value}日`
            }
            if (type === 'hour') {
                return `${value}时`
            }
            if (type === 'minute') {
                return `${value}分`
            }
            return value
        },
        openDatePicker(){
            this.tempCreateTime = Number(new Date())
            this.timePickerShow = true
        },
        onTimeConfirm(e){
            this.timePickerShow = false
            this.recordForm.createTime = formatTimestamp(e.value)
        }
    }
}
</script>

<style scoped>
.popup-body {
    padding: 20rpx;
}

.title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.switch-group {
    display: flex;
    align-items: center;
    margin-top: 20rpx;
}

.switch-label {
    margin-left: 20rpx;
    color: #666;
}

.footer-btns {
    margin-top: 30rpx;
}
</style>
